define(["dojo/json"], function(JSON){

   
    var clientId = '1006557476049-67480ie9isc917h9kgtm6je5d43dkg8j.apps.googleusercontent.com';
    var apiKey = 'AIzaSyDrgJBt3nVE9rkegoB8zETvp99WrgovwiE';
    var scopes = 'https://www.googleapis.com/auth/fusiontables';
 //   var src = "https://apis.google.com/js/client.js?onload=initializeAuth";
    var tableId =  "1EX8fAFpYb-oVM33jC72bHfSKUV-YOjMYc27MDA4";
    
    function loadjsfile(filename){
    	console.log("authenticateGoogle::loadjsfile");
    	  var fileref=document.createElement('script');
    	  fileref.setAttribute("type","text/javascript");
    	  fileref.setAttribute("src", filename);
    	 
    	 if (typeof fileref!="undefined")
    	  document.getElementsByTagName("head")[0].appendChild(fileref);
    }
    
    function init(){
    	console.log("authenticateGoogle::init");
    //	loadjsfile(src);
    	initializeAuth();
    	
    };

    function initializeAuth(){
    	console.log("authenticateGoogle::initializeAuth");
    	gapi.client.setApiKey(apiKey);
    	window.setTimeout(function() { auth(true); }, 1);
    };
    
    function auth(immediate) {
    	console.log("authenticateGoogle::auth: "+immediate);
        gapi.auth.authorize({
          client_id: clientId,
          scope: scopes,
          immediate: immediate
        }, handleAuthResult);
      };
    
    function handleAuthResult(authResult) {
    	console.log("authenticateGoogle::handleAuthResult");
        if (authResult) {
        	console.log("authenticateGoogle::handleAuthResult ok: ");
        } else {
        	console.log("authenticateGoogle::handleAuthResult ERROR: ");
        	auth(false); return false;
        }
      };
    
    // Send an SQL query to Fusion Tables.
    function query(query) {
    console.log("authenticateGoogle::query");
    console.log("query: "+query);
      var lowerCaseQuery = query.toLowerCase();
      var path = '/fusiontables/v1/query';
      var callback = function(element) {
        return function(resp) {
          var output = JSON.stringify(resp);
          console.log("authenticateGoogle::query output: "+output);
        };
      };
      if (lowerCaseQuery.indexOf('select') != 0 &&
          lowerCaseQuery.indexOf('show') != 0 &&
          lowerCaseQuery.indexOf('describe') != 0) {

        var body = 'sql=' + encodeURIComponent(query);
        runClientRequest({
          path: path,
          body: body,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': body.length
          },
          method: 'POST'
        }, callback('insert-data-output'));

      } else {
        runClientRequest({
          path: path,
          params: { 'sql': query }
        }, callback('select-data-output'));
      }
    };
    
    
    function runClientRequest(request, callback) {
    	console.log("authenticateGoogle::runClientRequest");
        var restRequest = gapi.client.request(request);
        restRequest.execute(callback);
      };
    
    /*
      	function insertData() {
    	  console.log("authenticateGoogle::insertData");
          var insert = [];
          insert.push('INSERT INTO ');
          insert.push(tableId);
          insert.push(' (Name, Age) VALUES (');
          insert.push("'" + name + "', ");
          insert.push(age);
          insert.push(')');
          query(insert.join(''));
        }
        */
    	function insertData(LatLng) {
      	  console.log("authenticateGoogle::insertData");
            var insert = [];
            insert.push('INSERT INTO 1EX8fAFpYb-oVM33jC72bHfSKUV-YOjMYc27MDA4 ');
            insert.push(' (ID, Nombre, Apellido, Date, Location) VALUES (7, ' );
            insert.push("'Desconocido', 'Desconocido', '01/01/1970', '" +LatLng.lat()+","+LatLng.lng());
            insert.push("')");
            query(insert.join(''));
          }
    //INSERT INTO 1EX8fAFpYb-oVM33jC72bHfSKUV-YOjMYc27MDA4 (ID, Nombre, Apellido, Date, Location) 
      //VALUES (3, 'Francisco', 'Garcia', '11/03/2013','40.420, -3.688')"
    
      return{
    	  	insertData : insertData,
      		runClientRequest : runClientRequest,
      		query : query,
      		handleAuthResult : handleAuthResult,
      		auth : auth,
      		initializeAuth: initializeAuth,
      		init : init,
      		loadjsfile : loadjsfile
      };
      
});